package com.iamteer.day24;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;

/**
发送图片的服务端
 */
public class ImageServer extends Thread{
	Socket socket;
	static long count = 0;
	static HashSet<String> ips = new HashSet<String>();
	
	public ImageServer(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			//3. 获取 Socket 的输出流对象
			OutputStream out = socket.getOutputStream();
			//4. 获取图片的输入流对象
			FileInputStream in = new FileInputStream("natureWinter.jpg"); 
			//5. 读取图片数据，并把数据写出
			byte[] buf = new byte[1024];
			int length = -1;
			while ((length = in.read(buf)) != -1) {
				out.write(buf, 0, length);
				out.flush();
			}
			String ip = socket.getInetAddress().getHostAddress();
			ips.add(ip);
			count++;
			System.out.println("[" + ip + "] 下载成功......共有 " +ips.size() + " 用户下载 " + count + " 次");
			
			//6. 关闭资源
			in.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws IOException {
//		//1. 建立 TCP 服务，并且监听一个端口
//		ServerSocket serverSocket = new ServerSocket(9090);
//		//2. 接受用户的连接
//		Socket socket = serverSocket.accept();
//		//3. 获取 Socket 的输出流对象
//		OutputStream out = socket.getOutputStream();
//		//4. 获取图片的输入流对象
//		FileInputStream in = new FileInputStream("natureWinter.jpg"); 
//		//5. 读取图片数据，并把数据写出
//		byte[] buf = new byte[1024];
//		int length = -1;
//		while ((length = in.read(buf)) != -1) {
//			out.write(buf, 0, length);
//			out.flush();
//		}
//		//6. 关闭资源
//		in.close();
//		serverSocket.close();
		
		ServerSocket serverSocket = new ServerSocket(9090);
		while (true) {
			Socket socket = serverSocket.accept();
			new ImageServer(socket).start();;
		}
	}

}
